<script setup>
    import { ref,reactive } from 'vue'
    import Editor from 'full-classic-editor'
    import { onMounted } from 'vue'
    import hljs from "highlight.js"
    import {ImageUploadAdapter} from 'full-classic-editor/src/plugin/ImageUploadAdapter'

    const editor = Editor
    let editorData = ref('<p>Content of the editor</p>');
    let codeBlocks = reactive([])
    let editorConfig = reactive({
        language: 'zh-cn'
    })
    onMounted(()=>{
        
    })

    const editorReady = (editor)=>{
        window.ckeditor = editor
        editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
            const uploadOptions = {
                uploadUrl: import.meta.env.VITE_BASE_URL+'/upload/ckEditor/simpleUploadAdapter',
                withCredentials: true,
                headers: {
                  Authorization: sessionStorage.getItem('authToken')
                }
            }
            return new ImageUploadAdapter(loader, uploadOptions)
        }
    }

    const highlightCode = ()=> {
        codeBlocks.value = []
        var editorMain = document.getElementsByClassName('ck ck-content ck-editor__editable')[0]
        let blocks = editorMain.querySelectorAll("pre code")
        for(var i=0; i<blocks.length;i++){
             var block = blocks[i]
             var dataLanguage =  block.parentNode.getAttribute('data-language')
             var className = block.getAttribute('class') + ' hljs'
            if(block.innerText==null || block.innerText=='' || block.innerText=='\n'){
                return
            }
            var highlightCode = hljs.highlightAuto(block.innerText).value;
            highlightCode = highlightCode.replaceAll('&quot;', '"').replaceAll('&#x27;', '\'')
            console.log(highlightCode)
            block.innerText = ''
            block.innerHTML = highlightCode
            codeBlocks.value.push({
                dataLanguage: dataLanguage,
                className: className,
                codeBlock: highlightCode
            })
            console.log(codeBlocks)
        }
    }

</script>
<template>
   <div id="editor-container">
        <Ckeditor :editor="editor" v-model="editorData" :config="editorConfig" @ready="editorReady"></Ckeditor>
        <el-button type="primary" @click="highlightCode" style="margin-top: 10px;margin-bottom: 10px;">代码高亮显示</el-button>
        <div class="code-area">
            <pre v-for="(item, index) in codeBlocks.value" :key="index" :data-language="item.dataLanguage">
                <code :class="item.className" style="text-align: left;" v-html="item.codeBlock"></code>
            </pre>
        </div>
   </div>
</template>